﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FinalProject.Services.Interfaces;
using FinalProject.Data.EntityRepositories.Interfaces;
using FinalProject.Data.DBInteractions.Interfaces;
using FinalProject.Entities;
using FinalProject.Data.Search;
using FinalProject.Data.Sort;

namespace FinalProject.Services.Services
{
    public class ClientService : IClientService
    {
        private readonly IClientRepository _repository;
        private readonly IUnitOfWork _unitOfWork;
        public ClientService(IClientRepository repository, IUnitOfWork unitOfWork)
        {
            this._repository = repository;
            this._unitOfWork = unitOfWork;
        }

        #region Members
        
        public PagedListResult<Entities.Client> GetAll()
        {
            var entities = _repository.Search(new SearchQuery<Client>());
            return entities;
        }

        public Entities.Client GetById(int id)
        {
            var entity = _repository.GetById(id);
            return entity;
        }

        public void Create(Entities.Client entity)
        {
            _repository.Add(entity);
            _unitOfWork.Commit();
        }

        public void Update(Entities.Client entity)
        {
            _repository.Update(entity);
            _unitOfWork.Commit();
        }

        public void Delete(int id)
        {
            var entity = _repository.GetById(id);
            _repository.Delete(entity);
            _unitOfWork.Commit();
        }

        public void Save()
        {
            _unitOfWork.Commit();
        }

        #endregion


        public IEnumerable<Entities.Client> GetLastAccessedClients(int x)
        {
            var query = new SearchQuery<Client>();
            query.AddSortCriteria(new FieldSortOrder<Client>("LastAccessed", SortDirection.Descending));
            query.Take = x;
            var entities = _repository.Search(query);
            return entities.Entities;
        }

        public PagedListResult<Entities.Client> SearchClient(string search)
        {
            var query = new SearchQuery<Client>();
            query.AddFilter(x => x.PersonName.FirstName.Contains(search)
                || x.PersonName.MiddleName.Contains(search)
                || x.PersonName.LastName.Contains(search)
                || x.Phone.Contains(search));
            var entities = _repository.Search(query);
            return entities;
        }


        public Entities.Client GetClientWithTickets(int id)
        {
            var query = new SearchQuery<Client>();
            query.IncludeProperties = "Tickets";
            query.AddFilter(x => x.Id == id);
            var entity = _repository.Search(query);
            return entity.Entities.FirstOrDefault();
        }
    }
}
